package socket001;

import java.io.*;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.Scanner;

public class Client1 {
    private Socket socket;

    public Client1(){
        try {
            System.out.println("正在连接服务端");
            socket = new Socket("localhost",8099);
            System.out.println("与服务端建立连接");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while(true) {
                ServerHanlder hanlder = new ServerHanlder();
                Thread t = new Thread(hanlder);
                t.setDaemon(true);
                t.start();

                OutputStream os = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(os, StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                PrintWriter pw = new PrintWriter(bw, true);
                Scanner scan = new Scanner(System.in);
                String line = scan.nextLine();

                if ("exit".equalsIgnoreCase(line)) {
                    System.out.println("退出聊天室");
                    break;
                }
                pw.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client1 c = new Client1();
        c.start();
    }

    private class ServerHanlder implements Runnable{
        public void run() {
            try {
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);
                String message;
                while ((message= br.readLine())!=null){
                    System.out.println(message);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
